﻿using System;
using Autofac;
using AutofacContrib.CommonServiceLocator;
using Microsoft.Practices.ServiceLocation;

namespace NQueries.Sample
{
    internal class Program
    {
        /// <summary>
        /// Sets up the dependency injection and logging.
        /// </summary>
        static void Bootstrapper()
        {
            // setup the dependencies required for NQueries
            ContainerBuilder containerBuilder = new ContainerBuilder();
            // map the data context
            containerBuilder.RegisterType<SimpleModelContext>().As<IDataContext>().ExternallyOwned().InstancePerDependency();
            IComponentContext componentContext = containerBuilder.Build();
            ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(componentContext));

            // lets log all our unit of works
            UnitOfWork.OnUnitOfWorkCreated += (sender, e) =>
            {
                if (!string.IsNullOrEmpty(e.Name))
                    Console.WriteLine("start <{0}>", e.Name);
            };

            // lets log the end and lifespan of each uow
            UnitOfWork.OnUnitOfWorkDisposed += delegate(object sender, UnitOfWorkDisposedEventArgs e)
            {
                if (!string.IsNullOrEmpty(e.Name))
                    Console.WriteLine("end <{0}> lifespan <{1:0} ms>", e.Name, e.Lifespan.TotalMilliseconds);
            };

            // recreate the test database
            Test.CreateDatabase();
        }

        static void Main()
        {
            Bootstrapper();

            Console.WriteLine();

            SampleSimpleOperations.Create();
            SampleSimpleOperations.Read();
            SampleSimpleOperations.NestedRead();
            SampleSimpleOperations.Update();
            SampleSimpleOperations.Delete();
            SampleSimpleOperations.GetbyIdFromSet();
            SampleSimpleOperations.UseCommandTimeout();
            SampleSimpleOperations.MultiInclude();
            SampleSimpleOperations.UpdateDetachedEntity();
            SampleSimpleOperations.VerifyRelationFixups();

            Console.WriteLine();

            SampleNonGenericQueries.ReadById();

            Console.WriteLine("\npress any key...");
            Console.ReadKey();
        }
    }
}